import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import Success from '../views/Success.vue';
import { useUserStore } from '../stores/userStore';
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/success', component: Success },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach((to: RouteLocationNormalized, _: RouteLocationNormalized, next: NavigationGuardNext) => {
  const userStore = useUserStore();
  if (to.path === '/success' && !userStore.isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});

export default router;